package org.apogee.mil.client.widgets;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.Point;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;

public class DialogHelper extends Dialog {

	private Widget layout;
	private String title;
	private int xPos;
	private int yPos;
	private boolean isMainPortal;

	public DialogHelper(String title, LayoutContainer layout) {
		this (title, layout, false);
	}

	public DialogHelper(String title, LayoutContainer layout, boolean isMainPortal) {
		this (title, layout.asWidget(), -1, -1, isMainPortal);
	}

	public DialogHelper(String title, LayoutContainer layout, int xPos, int yPos) {
		this(title, layout.asWidget(), xPos, yPos);
	}

	public DialogHelper(String title, Widget widget) {
		this (title, widget, -1, -1);
	}

	public DialogHelper(String title, Widget widget, int xPos, int yPos) {
		this(title, widget, -1, -1, false);
	}

	public DialogHelper(String title, Widget widget, int xPos, int yPos, boolean isMainPortal) {
		this.title = title;
		this.layout = widget;
		this.xPos = xPos;
		this.yPos = yPos;
		this.isMainPortal = isMainPortal;

		setButtonAlign(HorizontalAlignment.RIGHT);

	}


	@Override
	public void onRender(Element parent, int index) {
		super.onRender(parent, index);

		setHeading(title);
		setAutoHeight(true);
		setAutoWidth(true);

		add(layout);


		Button b = getButtonById(Dialog.OK);
		b.setText("Close");
		b.addSelectionListener(new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				remove(layout);
				hide();	
			}
		});



		addListener(Events.AfterLayout, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				if (isMainPortal) {
					setButtons("");

					GWT.log("Tool count " + getHeader().getToolCount());

					for(int i = 0; i < getHeader().getToolCount(); i++) {
						Component t = getHeader().getTool(i);
						getHeader().removeTool(t);
					}
				}
				if (xPos == -1 && yPos == -1) {
					center();
				} else {
					setPagePosition(new Point(xPos, yPos));
				}			
			}
		});
	}
}
